package com.xbongbong.parent.condition.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.parent.abstracts.AbstractConditionFieldHandler;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author 吴峰
 * @version v1.0
 * @date 2020/3/3 19:41
 * @since v1.0
 */
@Component
public class ConditionFormCreatorIdHandlerImpl extends AbstractConditionFieldHandler {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.CREATORID.getType());
    }

    @Override
    public Object handlerThisFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity,  FieldAttrEntity targetField,
                                       BusinessRuleInfoPojo businessRuleInfoPojo ) throws XbbException {
        return paasFormDataEntity.getCreatorId();
    }

    @Override
    public Object handlerFixedValue(FieldAttrEntity targetField, BusinessRuleInfoPojo businessRuleInfoPojo, FilterConditionsPoJo filterCondition) throws XbbException {
        return filterCondition.getValue();
    }

    @Override
    public Object handlerPreConditionValue(FieldAttrEntity thisField, BusinessRuleInfoPojo businessRuleInfoPojo, FilterConditionsPoJo filterCondition) throws XbbException {
        if (filterCondition.getValue() instanceof Map) {
            // 成员单选和部门单选
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(filterCondition.getValue()));
            return jsonObject.get("id");
        } else if (filterCondition.getValue() instanceof List) {
            List<DepartmentUserPojo> list = JSON.parseArray(JSON.toJSONString(filterCondition.getValue()), DepartmentUserPojo.class);
            if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), filterCondition.getSymbol())
                    || Objects.equals(ConditionEnum.NOEQUAL.getSymbol(), filterCondition.getSymbol())) {
                return list.get(0).getId();
            } else {
                List<Object> result = new ArrayList<>();
                list.forEach(item->{
                    result.add(item.getId());
                });
                return result;
            }

        }
        // 若放开了成员多选和部门多选，此处还要再做处理
        return filterCondition.getValue();
    }
}
